package com.hailiao.beidou.message.ui.page.search

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hailiao.beidou.message.data.contact.ContactRepository
import com.hailiao.beidou.message.data.db.entity.ContactEntity
import com.hailiao.beidou.message.data.db.entity.MatchedMessageCount
import com.hailiao.beidou.message.data.message.MessageRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 搜索
 * @Author d10ng
 * @Date 2024/3/2 14:35
 */
class SearchScreenViewModel: ViewModel() {

    // 搜索内容
    val searchFlow = MutableStateFlow("")

    // 搜索到的联系人列表
    val contactsFlow = MutableStateFlow(listOf<ContactEntity>())
    // 搜索到的消息数量列表
    val messageCountsFlow = MutableStateFlow(listOf<MatchedMessageCount>())

    init {
        viewModelScope.launch {
            searchFlow.collectLatest {
                if (it.isEmpty()) {
                    contactsFlow.emit(listOf())
                    messageCountsFlow.emit(listOf())
                } else {
                    contactsFlow.value = ContactRepository.search(it)
                    messageCountsFlow.value = MessageRepository.searchCount(it)
                }
            }
        }
    }

    /**
     * 更新搜索内容
     * @param value String
     */
    fun onUpdateSearch(value: String) {
        searchFlow.value = value
    }
}